import router from './router'
import store from './store'
import { SQLTable } from '../public/js/paramarr'
import Global from '../public/js/global'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/design'] // no redirect whitelist

// 进入页面之前先把store中的SystemConfigArr重新赋值给SystemConfig
const reverseData = () => {
  const SystemConfigArr = store.state.systemConfig.SystemConfigArr
  if (SystemConfigArr.length) {
    const nodeMap = new Map()
    const nodes = []
    SystemConfigArr.forEach(item => {
      const node = {}
      for (const key in item) {
        node[key] = item[key]
      }
      nodes.push(node)
      nodeMap.set(item.name, node)
    })

    store.commit('systemConfig/setSystemConfig', nodeMap)
  }
}

router.beforeEach(async(to, from, next) => {
  // 进入页面之前先把store中的SystemConfigArr重新赋值给SystemConfig
  reverseData()

  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken('Token')
  // console.log(hasToken);

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        // get user info
        store.dispatch('user/getInfo').then(vPar => {
          document.title = getPageTitle(to.meta.title, store.getters.title)
          var table = new SQLTable(vPar.getTable('k_menu'))
          var nodes = []
          var nodeMap = new Map()
          while (!table.eof()) {
            var pnode = Global.getTreeviewPNode(nodeMap, nodes, table.getValueByName('PID'))
            var node = {}
            var path = ''
            var url = table.getValueByName('url')
            node['id'] = table.getValueByName('ID')
            node['name'] = table.getValueByName('title')
            node['text'] = table.getValueByName('title')
            node['level'] = table.getValueByName('aLevel')
            if (url !== '') {
              var name = url.split('/').slice(-1).join()
              path = '/' + name.substr(0, name.lastIndexOf('.'))
            }
            node['path'] = path
            table.next()
            // add
            pnode.push(node)
            nodeMap.set(table.getValueByName('ID'), node)
          }
          store.commit('user/SET_LIST', nodes)
        })

        next()
      } catch (error) {
        // remove token and go to login page to re-login
        await store.dispatch('user/resetToken')
        Message.error(error || 'Has Error')
        // next(`/login?redirect=${to.path}`)
        next(`/login`)
        NProgress.done()
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
